package cn.liujianbo.example.base;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 刘建波
 * @date 2021-01-23 10:12
 */
public class CyclicBarrierDemo {

    private CyclicBarrierDemo(){
        System.out.println("私有构造方法被调用");
    }

    public static void main(String[] args) {
        // 声明数量为2的栅栏
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, ()->{
            System.out.println("开会！");
        });

        new Thread(() -> {
            String tName = Thread.currentThread().getName();
            System.out.println(tName + "消费一个栅栏");
            try {
                cyclicBarrier.await();
                System.out.println(tName + "栅栏被释放，继续执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }, "t1").start();

        new Thread(() -> {
            String tName = Thread.currentThread().getName();
            System.out.println(tName + "消费一个栅栏");
            try {
                cyclicBarrier.await();
                System.out.println(tName + "栅栏被释放，继续执行！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "t2").start();


        new Thread(() -> {
            String tName = Thread.currentThread().getName();
            System.out.println(tName + "消费一个栅栏");
            try {
                cyclicBarrier.await();
                System.out.println(tName + "栅栏被释放，继续执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }, "t3").start();

        new Thread(() -> {
            String tName = Thread.currentThread().getName();
            System.out.println(tName + "消费一个栅栏");
            try {
                cyclicBarrier.await();
                System.out.println(tName + "栅栏被释放，继续执行！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "t4").start();
    }
}
